package com.example.heartprotectionserver.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.heartprotectionserver.model.User;
import com.example.heartprotectionserver.mapper.UserMapper;
import com.example.heartprotectionserver.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张力文
 * @since 2023-07-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public Integer login(String name, String password) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName,name);
        List<User> users = userMapper.selectList(lqw);
        if (users.size()!=0){
//            用md5加密之后跟数据库进行比较
            if (users.get(0).getPassword().equals(SecureUtil.md5(password))){
                return 1;//密码正确
            } else {
                return 0;//密码错误
            }
        } else {
            return -1;//用户不存在
        }
    }

    @Transactional
    @Override
    public Integer regist(User user) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName,user.getName());
        List<User> users = userMapper.selectList(lqw);
        if(users.size()!=0){
            return -1;//用户名已存在
        } else {
//            使用MD5进行密码加密
            user.setPassword(SecureUtil.md5(user.getPassword()));
            int insert = userMapper.insert(user);
            return insert;//为0则插入失败，否则为成功
        }

    }
}
